package com.test;

import com.SortTestHelper;

import java.util.Arrays;

public class InsertionSort {
    public static void main(String[] args) {
        int N = 1000000;
        Integer[] arr = SortTestHelper.generateRandomArray(N, 0, 100000);
        System.out.println(Arrays.toString(arr));
        long begin = System.currentTimeMillis();
        InsertionSort.sort2(arr);
        long end = System.currentTimeMillis();
        System.out.println(end - begin);
    }

    public static void sort(Comparable[] arr) {
        int n = arr.length;
        int num = 0;
        for (int i = 1; i < n; i++) {
            for (int j = i; j > 0; j--) {
                num++;
                if (arr[j].compareTo(arr[j - 1]) < 0) {
                    swap(arr, j, j - 1);
                    System.out.println(Arrays.toString(arr));
                } else {
                    System.out.println(Arrays.toString(arr));
                    break;
                }
            }
        }
    }

    public static void sort2(Comparable[] arr) {
        int n = arr.length;
        int num = 0;
        for (int i = 1; i < n; i++) {
            for (int j = i; j > 0 && arr[j].compareTo(arr[j - 1]) < 0; j--) {
                num++;
                swap(arr, j, j - 1);
            }
        }
        System.out.println(Arrays.toString(arr));
    }

    private static void swap(Comparable[] arr, int i, int j) {

        Comparable t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }
}
